﻿package kizzo.utils 
{
	import flash.events.Event;
	
	public class GlobalEventDispatcher 
	{	
		
		
		private static var event_array:Array = [];
		
		
		public function GlobalEventDispatcher() 
		{			
		}		
		
		
		public static function addEventListener(object:*, type:String, handler:Function):void
		{	
			if (event_array[type] == null)			
				event_array[type] = [];
			
			for (var i:uint = 0; i < event_array[type].length; i++)
			if (event_array[type][i].object == object)
				return;
						
			event_array[type].push({object:object, handler:handler});
		}		
		
		
		public static function removeEventListener(object:*, type:String):void
		{
			//trace("removing " + type);
			for (var i:uint = 0; i < event_array[type].length; i++)
			if (event_array[type][i].object == object)
				event_array[type].splice(i, 1);			
		}
		
		
		public static function dispatchEvent(event:CustomEvent):void
		{	
			var cq:CommandQueue = new CommandQueue();
			if (event_array[event.type])
			{
				for (var i:uint = 0; i < event_array[event.type].length; i++)
				{	
					//trace(event.type + " called for " + event_array[event.type][i].object);
					cq.add(new Command(event_array[event.type][i].handler, [event], Command.SYNC, event_array[event.type][i].object));
				}
			}
			cq.execute();			
		}
		
		public static function listEventSubscribers(type:String):void
		{			
			for (var i:uint = 0; i < event_array[type].length; i++)
				trace(event_array[type][i].object + " subscribed for " + type);				
			//trace("subscribers for " + type + " " + event_array[type].length);
		}
		
		public static function traceAll():void
		{
			var count:uint = 0;
			for (var type:String in event_array)
			{
				trace("Subscribers for event:" + type);
				for (var i:uint = 0; i < event_array[type].length; i++)
					trace(event_array[type][i].object);
				trace("Number:" + i);
				count += i;
			}
			trace ("Total:" + count);
		}
		
	}	
}